﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace EcodexIntegrationSample
{
    class frmCancelaOtrosController
    {
        private View.IfrmCancelaOtros _view;

        public frmCancelaOtrosController(View.IfrmCancelaOtros view)
        {
            _view = view;
            _view.onCancelaOtros += View_onCancelaOtros;
        }

        void View_onCancelaOtros(object sender, EventArgs e)
        {
            using (var Cancelacion = new SrvCancelacion.CancelacionesClient())
            {
                long trsId = _view.TransaccionId;
                string token = string.Empty;

                string Error;
                Utils.Utilerias Util = new Utils.Utilerias(_view);
                Error = Util.CreateToken(_view.RFCEmisor, trsId, ref token);
                if (!string.IsNullOrEmpty(Error))
                {
                    _view.ShowUnknownError(Error);
                    return;
                }
                try
                {
                    var respuesta = Cancelacion.CancelaOtros(_view.RFCEmisor, _view.RFCReceptor, token, ref trsId, _view.UUID);
                    foreach (var item in respuesta)
                    {
                        _view.Estatus = item.Estatus;
                        _view.UUID = item.UUID;
                    }
                }
                catch (FaultException<SrvCancelacion.FallaValidacion> validationFault)
                {
                    using (var errorForm = new Forms.Error(TranslateFault.ToValidationError(validationFault.Detail)))
                    {
                        errorForm.ShowDialog();
                    }
                }
                catch (FaultException<SrvCancelacion.FallaServicio> serviceFault)
                {
                    using (var errorForm = new Forms.Error(TranslateFault.ToServiceError(serviceFault.Detail)))
                    {
                        errorForm.ShowDialog();
                    }
                }
                catch (FaultException<SrvCancelacion.FallaSesion> sessionFault)
                {
                    using (var errorForm = new Forms.Error(TranslateFault.ToSessionError(sessionFault.Detail)))
                    {
                        errorForm.ShowDialog();
                    }                    
                }
                catch (TimeoutException)
                {
                    _view.ShowUnknownError("Error de tiempo de espera del servicio");
                }
                catch (Exception ex)
                { _view.ShowUnknownError(ex.Message); }

            }
        }
    }
}
